package com.kb.design.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kb.design.constant.Constants;
import com.kb.design.dto.ForestallOrderDTO;
import com.kb.design.entity.DesignDictData;
import com.kb.design.entity.DesignRequirement;
import com.kb.design.entity.DesignResponsiblePerson;
import com.kb.design.entity.DesignReviewData;
import com.kb.design.enums.DesignStatus;
import com.kb.design.enums.ReviewType;
import com.kb.design.mapper.postgreSQL.DesignRequirementMapper;
import com.kb.design.mapper.postgreSQL.DesignResponsiblePersonMapper;
import com.kb.design.mapper.postgreSQL.DesignReviewMapper;
import com.kb.design.service.CustomUserService;
import com.kb.design.service.DesignReviewService;
import com.kb.design.util.CommonUtil;
import com.kb.design.vo.ReviewInfoVO;
import com.kb.design.vo.ReviewVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther:chenzx
 * @Date:2023/11/13
 * @Description:
 */
@Service
@DS("slave-1")
public class DesignReviewServiceImpl extends ServiceImpl<DesignReviewMapper, DesignReviewData>  implements DesignReviewService {


    @Resource
    private DesignReviewMapper designReviewMapper;
    @Resource
    private ProjectServiceImpl projectServiceImpl;
    @Resource
    private DesignRequirementMapper designRequirementMapper;
    @Resource
    private CustomUserService userService;
    @Resource
    private DesignResponsiblePersonMapper responsiblePersonMapper;
    /**
     *提交审核
     *
     */
    @Override
    @DSTransactional
    public boolean insert(ReviewVO reviewVO) {
        CommonUtil.webLog("DesignReviewServiceImpl.insert",reviewVO);


        List<DesignDictData> layoutApproval = reviewVO.getLayoutApproval();
        if (CollectionUtil.isNotEmpty(layoutApproval)){
            List<DesignReviewData> designReviewDataList = BeanUtil.copyToList(layoutApproval, DesignReviewData.class);
            designReviewDataList.forEach(e -> {
                e.setType("layoutApproval");
                e.setProjectId(reviewVO.getProjectId());
                e.setId(null);
            });
            this.saveBatch(designReviewDataList);
        }
        List<DesignDictData> wiringApproval = reviewVO.getWiringApproval();
        if (CollectionUtil.isNotEmpty(wiringApproval)){
            List<DesignReviewData> wiringApprovalList = BeanUtil.copyToList(wiringApproval, DesignReviewData.class);
            wiringApprovalList.forEach(e -> {
                e.setType("wiringApproval");
                e.setProjectId(reviewVO.getProjectId());
                e.setId(null);

            });
            this.saveBatch(wiringApprovalList);
        }


        //修改审批状态 根据提交的数据判断 改流程主表的状态为客户确认
        DesignRequirement requirement = new DesignRequirement();
        requirement.setReviewType(ReviewType.WIRING_APPROVAL.getValue());
        if (CollectionUtil.isNotEmpty(wiringApproval)){
            requirement.setReviewType(ReviewType.APPROVAL_COMPLETE.getValue());

        }
        LambdaQueryWrapper<DesignRequirement> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignRequirement::getProjectId,reviewVO.getProjectId());
        requirement.setDesignStatus(DesignStatus.DESIGN.getIndex());
        designRequirementMapper.update(requirement,queryWrapper);
        //修改子表上一节点状态为完成
        DesignResponsiblePerson responsiblePerson = new DesignResponsiblePerson();
        LambdaQueryWrapper<DesignResponsiblePerson> query = Wrappers.lambdaQuery();
        query.eq(DesignResponsiblePerson::getNodeStatus,DesignStatus.DESIGN.getIndex())
                .eq(DesignResponsiblePerson::getProjectId,reviewVO.getProjectId());
        responsiblePerson.setIsComplete(Constants.YES_COMPLETE);

        responsiblePersonMapper.update(responsiblePerson,query);
        //新增下一节点数据 封装节点不需要新增
        DesignResponsiblePerson designResponsiblePerson = new DesignResponsiblePerson();
//        designResponsiblePerson.setNodeResponsiblePersonId(reviewVO.getPersonResponsibleId());
            designResponsiblePerson.setNodeStatus(DesignStatus.getNextStatusByIndex(reviewVO.getDesignStatus()).getIndex());
            designResponsiblePerson.setDel(Constants.DEL_FLAG_NO)
                    .setProjectId(reviewVO.getProjectId())
                    .setIsComplete(Constants.NO_COMPLETE)
                    .setNodeStatus(DesignStatus.DESIGN.getIndex());
//                            .setNodeResponsiblePersonName(userService.queryNickName(reviewVO.getPersonResponsibleId()));

            responsiblePersonMapper.insert(designResponsiblePerson);

        return true;
    }

    @Override
    public ReviewInfoVO queryReview(ForestallOrderDTO forestallOrderDTO) {
        LambdaQueryWrapper<DesignReviewData> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignReviewData::getProjectId,forestallOrderDTO.getProjectId());
        List<DesignReviewData> designReviewData = designReviewMapper.selectList(queryWrapper);
        ReviewInfoVO reviewVO = new ReviewInfoVO();
        if (CollectionUtils.isNotEmpty(designReviewData)) {
            Map<String, List<DesignReviewData>> groupedByGrade = designReviewData.stream()
                    .collect(Collectors.groupingBy(DesignReviewData::getType));
            // 使用 getOrDefault 简化 if 判断
            reviewVO.setLayoutApproval(groupedByGrade.getOrDefault("layoutApproval", Collections.emptyList()));
            reviewVO.setWiringApproval(groupedByGrade.getOrDefault("wiringApproval", Collections.emptyList()));
        }
        return reviewVO;
    }

    @Override
    public Integer queryReviewStatus(Long projectId) {
        LambdaQueryWrapper<DesignReviewData> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignReviewData::getProjectId,projectId);
        List<DesignReviewData> designReviewData = designReviewMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(designReviewData)){
            return ReviewType.LAYOUT_APPROVAL.getValue();
        }
        DesignReviewData designReview = designReviewData.get(designReviewData.size()-1);
        return Integer.valueOf(designReview.getStatus());
    }
}
